var lineMarkers = []; // 路径线

// 人步行速度 80米/分钟
const walkSpeed = 80;
// 方向对应的图标
const directionImg = {
  '左': 'left.png',
  '左前': 'left-front.png',
  '左后': 'left-back.png',
  '右前': 'right-front.png',
  '右后': 'right-back.png',
  '右': 'right.png',
  '前': 'front.png',
  '终': 'end-icon.png',
}

var searchAnalyser; // 搜索分析对象
var routeAnalyser;           // 路径分析对象
var start;              // 起点
var dest;               // 终点
var startMarker, endMarker; // 起点终点图标
var clickPoint; // 点击地图的点坐标
var mode = fengmap.FMNaviMode.MODULE_SHORTEST; // 最短路径
var priority = fengmap.FMNaviPriority.PRIORITY_LIFTFIRST; // 直梯优先

const enumFMRouteResult = {
  4: {
    description: "表示失败，无法到达的标识",
    value: 4,
    errType: "ROUTE_FAILED_CANNOT_ARRIVE"
  },
  9: {
    description: "表示失败，出入口计算失败",
    value: 9,
    errType: "ROUTE_FAILED_ENTRANCE"
  },
  3: {
    description: "表示失败，终点不在地图底板内",
    value: 3,
    errType: "ROUTE_FAILED_NO_DATA_DEST"
  },
  2: {
    description: "表示失败，起点不在地图底板内",
    value: 2,
    errType: "ROUTE_FAILED_NO_DATA_START"
  },
  7: {
    description: "表示失败，终点不可达",
    value: 7,
    errType: "ROUTE_FAILED_NO_DEST_ARRIVAL"
  },
  6: {
    description: "表示失败，起点不可达",
    value: 6,
    errType: "ROUTE_FAILED_NO_START_ARRIVAL"
  },
  8: {
    description: "表示失败，跨层计算失败",
    value: 8,
    errType: "ROUTE_FAILED_OUTLINE"
  },
  5: {
    description: "表示失败，途经点计算错误",
    value: 5,
    errType: "ROUTE_FAILED_WAYPOINT_CALCULATE_ERROR"
  },
  1: {
    description: "表示路线计算成功的标识",
    value: 1,
    errType: "ROUTE_SUCCESS"
  }
}



function initNaviRouter(callback) {
  // 初始化路径分析类
  routeAnalyser = new fengmap.FMNaviWalkAnalyser({ map: map }, () => {
    console.log('路径分析类创建成功')
    callback && callback()
  }, () => {
    console.error('路径分析类创建失败')
  });
}
// 处理骑手手上的订单
function handleRiderHandOrders(data) {


// #region 模拟开始


  // data = [
  //   {
  //     "orderNumber": "1848320662779858944",
  //     "shopName": "大兴城里机场美食城店",
  //     "shopTel": "15696943881",
  //     "shopLat": 31.15285677120552,
  //     "shopLng": 121.80257914420719,
  //     "shopX": 1.3559001085753119E7,
  //     "shopY": 3652616.455924955,
  //     "shopLevel": 4,
  //     "shopMapId": "1792818455411253249",
  //     "userLat": 31.153851889373705,
  //     "userLng": 121.80132239530288,
  //     "userX": 1.3558861185105056E7,
  //     "userY": 3652745.8996,
  //     "userLevel": 4,
  //     "userMapId": "1792818455411253249",
  //     "nickName": "测试陈",
  //     "userMobile": "18621191610",
  //     "riderName": "范承志",
  //     "riderPhone": "17877777777"
  //   }
  // ]
  // data[0].shopLng = 121.8023428510475
  // data[0].shopLat = 31.15109253563084
  // data[0].shopLevel = 4

  // data[0].userLng = 121.81266090497117
  // data[0].userLat = 31.137475961290097
  // data[0].userLevel = 6


// #endregion 模拟结束








  // 切换骑手的时候 进行页面图层的删除
  removeRiderHandOrders();
  let qcsData = []; //起点
  let ucsData = []; //终点
  data.forEach((f, index) => {
    // 起点终点线
    naviAndDrawLine({
      startLng: f.shopLng,
      startLat: f.shopLat,
      startX: f.shopX,
      startY: f.shopY,
      startLevel: f.shopLevel,
      destLng: f.userLng,
      destLat: f.userLat,
      destX: f.userX,
      destY: f.userY,
      destLevel: f.userLevel,
      index
    }, f)
    // 进行中的商户点 - 起点
    qcsData.push({
      ...latlngToMapXyCoords({
        lng: f.shopLng,
        lat: f.shopLat
      }),
      level: f.shopLevel || 1,
      extra: f
    })
    // 用户点 - 终点
    ucsData.push({
      ...latlngToMapXyCoords({
        lng: f.userLng,
        lat: f.userLat
      }),
      level: f.userLevel || 1,
      extra: f
    })
  })
  // 进行中的商户点 - 起点
  initStartLayer(qcsData)
  // 用户点 - 终点
  initUserLayer(ucsData);
}
// 移除图层
function removeRiderHandOrders() {
  if (lineMarkers.length) {
    lineMarkers.forEach(f => {
      f && f.remove();
    })
  }
  lineMarkers = [];
  if (userMarkers.length) {
    userMarkers.forEach(f => {
      f && f.remove();
    })
  }
  userMarkers = [];
  if (startMarkers.length) {
    startMarkers.forEach(f => {
      f && f.remove();
    })
  }
  startMarkers = [];
}
// 规划路径
async function naviAndDrawLine(params, rootData) {
  let necessaryPointRes = await $parent_this.$http({
    url: $parent_this.$http.adornUrl(`/platform/rider/essential`),
    method: "post",
    data: {
      fromFloor: map.getFloor(params.startLevel || 1).name,
      toFloor: map.getFloor(params.destLevel || 1).name,
      fromX: params.startX,
      toX: params.destX,
      fromY: params.startY,
      toY: params.destY,
    }
  })
  let naviRequest = {
    start: {
      lng: params.startLng,
      lat: params.startLat,
      // ...latlngToMapXyCoords({
      //     // lng: 121.79967448316701,
      //     // lat: 31.15246233922889,
      //     lng: params.startLng,
      //     lat: params.startLat,
      // }),
      x: params.startX,
      y: params.startY,
      level: params.startLevel || 1,
      size: 32,
      height: 3,
      url: '../static/start-map-icon.png',
    },
    dest: {
      lng: params.destLng,
      lat: params.destLat,
      // ...latlngToMapXyCoords({
      //     // lng: 121.80285638244966,
      //     // lat: 31.154321238882464,
      //     lng: params.destLng,
      //     lat: params.destLat,
      // }),
      x: params.destX,
      y: params.destY,
      level: params.destLevel || 1,
      url: '../static/dest-map-icon.png',
      size: 32,
      height: 3,
    },
    mode: 1,
    priority: 2,
    viapoints: necessaryPointRes.data
  }
  console.log("naviRequest", naviRequest);
  routeAnalyser.route(naviRequest, (result) => {
    console.log(result);
    drawRouteLine(result, params.index, rootData);
    // walkPathScheme(result);//走路的方案
  }, (fault) => {
    console.error("error:", fault, '====>', enumFMRouteResult[fault]);
  })
}

function drawRouteLine(result, index, rootData) {
  segments = [];
  let subs = result.subs;
  var segment = new fengmap.FMSegment();
  for (let index = 0; index < subs.length; index++) {
    const leg = subs[index];
    if (leg.levels[0] === leg.levels[1]) {
      leg.waypoint.points.forEach(point => {
        point.z = 0.5;
      });
      if (segment.points) {
        let points = [];
        points.push(...leg.waypoint.points);
        points.splice(0, 1);
        segment.points = segment.points.concat(points);
      } else {
        segment.points = leg.waypoint.points;
      }
      segment.level = leg.levels[0];
      if (index == subs.length - 1) {
        segments.push(segment);
      }
    } else {
      segments.push(segment);
      segment = new fengmap.FMSegment();
    }
  }
  lineMarkers[index] = new fengmap.FMLineMarker({
    width: 8,
    color: '#1890FF',
    borderColor: '#FFFFFF00',
    segments: segments,
    smooth: true,
    animate: true,
    // type: fengmap.FMLineType.FULL,
    // gradient: { 0.0: 'rgb(24,144,255)', 0.25: 'rgb(24,144,255)', 0.5: 'rgb(24,144,255)', 0.75: 'rgb(24,144,255)', 1.0: 'rgb(24,144,255)' },
  })
  lineMarkers[index]._extra = {
    lineMarkerIndex: index,
    ...rootData
  }
  lineMarkers[index].nodeType = "riderLine"
  lineMarkers[index].addTo(map)
}


function changeLineColor(e) {
  let index = e._extra.lineMarkerIndex
  let lightColor = "#7fff00"
  console.log("切换这条线的颜色", e);
  if (lineMarkers[index].highlight) {
    lineMarkers.forEach(f => {
      f.color = "#1890FF"
      f.height = 1
      f.visible = true;
    })
    lineMarkers[index].highlight = false;
    return
  }
  lineMarkers.forEach(f => {
    f.color = "#1890FF70"
    f.height = 1
  })
  lineMarkers[index].color = lightColor;
  lineMarkers[index].visible = true;
  lineMarkers[index].highlight = true;
}

function walkPathScheme(result) {
  $('#navi_result').css('display', 'block')
  $('#navi_result').empty()
  $('#navi_result').append(`<div class='navi_result_title'><span class='navi_result_normal'>全程</span> <span class='navi_result_highlight'>${result.distance.toFixed(2)}</span><span class='navi_result_normal'>米，预计用时</span><span class='navi_result_highlight'>${Math.ceil(result.distance / walkSpeed)}</span><span class='navi_result_normal'>分钟</span></div>`)
  $('#navi_result').append(`<ul class="layui-timeline" id='timeline'>`)
  result.subs.forEach(item => {
    console.log(item);
    // 路线的汉语方向
    const direction = item.waypoint.direction.zh[1]
    const node = $(`<li class="layui-timeline-item" onclick>
                            <i class="layui-icon layui-timeline-axis"></i>
                                <div class="layui-timeline-content layui-text">
                                    <img src='https://developer.fengmap.com/fmAPI/images/navi/${directionImg[direction]}' width='20px' height='20px'/>
                                    <div class='navi_route_desc'>${item.instruction.zh}</div>
                                </div>
                        </li>`)
    node.click(function () { onRouteClick(item) })
    $('#timeline').append(node)
  })
}

// 路线被选中
function onRouteClick(item) {
  const points = item.waypoint.points;
  const routecenter = { x: (points[0].x + points[1].x) / 2, y: (points[0].y + points[1].y) / 2 }
  map.setCenter({
    x: routecenter.x, y: routecenter.y, animate: true, finish: function () {
      map.setZoom({ zoom: 21, animate: true })
    }
  })
}
